<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>项目管理 - 系统管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        .project-filter {
            background: #f8f8f8;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .project-stats {
            margin-bottom: 15px;
        }

        .status-design {
            color: #1E9FFF;
        }

        .status-accept {
            color: #5FB878;
        }

        .status-audit {
            color: #FFB800;
        }

        .status-unknown {
            color: #999;
        }
    </style>
</head>

<body>
    <div class="layui-container">
        <div class="layui-card">
            <div class="layui-card-header">
                <span style="font-size: 18px; font-weight: bold;">项目管理</span>
                <div style="float: right;">
                    <button class="layui-btn layui-btn-sm" onclick="refreshProjects()">
                        <i class="layui-icon layui-icon-refresh"></i>刷新
                    </button>
                </div>
            </div>
            <div class="layui-card-body" style="font-size: 14px;">
                <!-- 筛选区域 -->
                <div class="project-filter">
                    <div class="layui-form">
                        <div class="layui-row">
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">建设单位</label>
                                    <div class="layui-input-inline">
                                        <select name="orgName" id="orgSelect" style="width: 200px;">
                                            <option value="">加载中...</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">项目状态</label>
                                    <div class="layui-input-inline">
                                        <select name="projectState" id="stateSelect" style="width: 150px;">
                                            <option value="">全部状态</option>
                                            <option value="1">设计中</option>
                                            <option value="2">验收中</option>
                                            <option value="3">审计中</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">关键词</label>
                                    <div class="layui-input-inline" style="width: 200px;">
                                        <input type="text" name="search" id="search-input" placeholder="输入工程编码/名称"
                                            class="layui-input">
                                    </div>
                                    <button class="layui-btn layui-btn-normal" onclick="searchProjects()">搜索</button>
                                    <button class="layui-btn layui-btn-primary" onclick="clearSearch()">清空</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 统计信息 -->
                <div class="layui-row project-stats">
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-header">总项目数</div>
                            <div class="layui-card-body" id="totalProjectCount" style="color: #1E9FFF;">
                                加载中...
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-header">设计中</div>
                            <div class="layui-card-body" id="designCount" style="color: #1E9FFF;">
                                加载中...
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-header">验收中</div>
                            <div class="layui-card-body" id="acceptCount" style="color: #5FB878;">
                                加载中...
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-header">审计中</div>
                            <div class="layui-card-body" id="auditCount" style="color: #FFB800;">
                                加载中...
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 项目表格 -->
                <div class="layui-table-container">
                    <table id="projectTable" lay-filter="projectTable"></table>
                </div>
            </div>
        </div>
    </div>

    <!-- 项目操作工具栏模板 -->
    <script type="text/html" id="projectToolbar">
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
    </script>

    <!-- 状态列模板 -->
    <script type="text/html" id="projectStateTpl">
        {{# if(d.project_state === 1){ }}
            <span class="status-design">设计中</span>
        {{# } else if(d.project_state === 2){ }}
            <span class="status-accept">验收中</span>
        {{# } else if(d.project_state === 3){ }}
            <span class="status-audit">审计中</span>
        {{# } else { }}
            <span class="status-unknown">未知</span>
        {{# } }}
    </script>

    <!-- 时间列模板 -->
    <script type="text/html" id="timeTpl">
        {{# if(d.created_at){ }}
            {{ layui.util.toDateString(d.created_at) }}
        {{# } else { }}
            -
        {{# } }}
    </script>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/js/auth-utils.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        layui.use(['table', 'form', 'util'], function () {
            var table = layui.table;
            var form = layui.form;
            var util = layui.util;
            var $ = layui.$;

            var isComposing = false;
            var projectTableData = [];

            function initProjectTable() {
                var loading = layui.layer.load(1);

                http.get(API_CONFIG.ADMIN.PROJECTS + '?limit=1000', {
                    org_code: '',
                    design_type: API_CONFIG.DESIGNTYPE.All
                })
                    .then(function (res) {
                        layui.layer.close(loading);
                        projectTableData = res.data || [];

                        layui.table.render({
                            elem: '#projectTable',
                            data: projectTableData,
                            page: {
                                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'], // 完整的布局
                                prev: '上一页',
                                next: '下一页',
                                groups: 5, // 连续显示页码数
                                first: '首页',
                                last: '尾页'
                            },
                            limits: [10, 20, 50, 100],
                            limit: 10,
                            maxHeight: 'full-360',
                            cols: [[
                                { type: 'numbers', title: '序号', width: 60 },
                                { field: 'design_code', title: '设计编码', width: 150 },
                                { field: 'name', title: '项目名称', minWidth: 360 },
                                { field: 'org_name', title: '建设单位', width: 100 },
                                { field: 'designer', title: '设计人员', width: 160 },
                                {
                                    field: 'project_state',
                                    title: '状态',
                                    width: 80,
                                    align: 'center',
                                    templet: '#projectStateTpl'
                                },
                                {
                                    field: 'created_at',
                                    title: '创建时间',
                                    width: 100,
                                    templet: '#timeTpl'
                                },
                                {
                                    field: 'updated_at',
                                    title: '更新时间',
                                    width: 100,
                                    templet: function (d) {
                                        return d.updated_at ? layui.util.toDateString(d.updated_at) : '-';
                                    }
                                },
                                { fixed: 'right', title: '操作', toolbar: '#projectToolbar', width: 80, align: 'center' }
                            ]]
                        });

                        // 更新统计信息
                        updateProjectStats(projectTableData);
                    })
                    .catch(function (err) {
                        layui.layer.close(loading);
                        layui.layer.msg('加载项目数据失败');
                    });
            }

            // 初始化
            initProjectTable();
            loadOrgList();
            loadProjectStats();

            // 项目表格工具条事件
            table.on('tool(projectTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'delete') {
                    deleteProject(data);
                }
            });

            // 表单事件
            form.on('select(orgName)', function (data) {
                filterProjects();
            });

            form.on('select(projectState)', function (data) {
                filterProjects();
            });

            // 搜索相关事件
            bindSearchEvents();

            // 初始化项目表格

            // 加载组织列表
            function loadOrgList() {
                http.get(API_CONFIG.ENDPOINTS.GET_ORG_LIST)
                    .then(function (res) {
                        var orgList = res.data || [];
                        var orgSelect = document.getElementById('orgSelect');

                        orgSelect.innerHTML = '<option value="">全部组织</option>';
                        orgList.forEach(function (org) {
                            var option = document.createElement('option');
                            option.value = org.org_code;
                            option.textContent = org.org_name;
                            orgSelect.appendChild(option);
                        });

                        layui.form.render('select');
                    })
                    .catch(function (err) {
                        console.error('获取组织列表失败:', err);
                    });
            }

            // 绑定搜索事件
            function bindSearchEvents() {
                var searchTimer;

                $('#search-input')
                    .on('compositionstart', function () {
                        isComposing = true;
                    })
                    .on('compositionend', function () {
                        isComposing = false;
                        clearTimeout(searchTimer);
                        searchTimer = setTimeout(filterProjects, 500);
                    })
                    .on('input', function () {
                        if (!isComposing) {
                            clearTimeout(searchTimer);
                            searchTimer = setTimeout(filterProjects, 500);
                        }
                    })
                    .on('keydown', function (e) {
                        if (e.keyCode === 13) {
                            clearTimeout(searchTimer);
                            filterProjects();
                        }
                    });
            }

            // 筛选项目
            function filterProjects() {
                var orgCode = $('#orgSelect').val();
                var state = $('#stateSelect').val();
                var keyword = $('#search-input').val().trim();

                if (!projectTableData.length) return;

                var filteredData = projectTableData.filter(item => {
                    // 组织筛选
                    var orgMatch = !orgCode || item.org_code === orgCode;

                    // 状态筛选
                    var stateMatch = !state || item.project_state == state;

                    // 关键词筛选
                    var keywordMatch = true;
                    if (keyword) {
                        var matchCode = item.design_code && item.design_code.toString().includes(keyword);
                        var matchName = item.name && item.name.toString().includes(keyword);
                        keywordMatch = matchCode || matchName;
                    }

                    return orgMatch && stateMatch && keywordMatch;
                });

                layui.table.reload('projectTable', {
                    data: filteredData,
                    //page: false
                });

                // 更新筛选后的统计
                updateProjectStats(filteredData);
            }

            // 搜索项目
            window.searchProjects = function () {
                filterProjects();
            }

            // 清空搜索
            window.clearSearch = function () {
                $('#orgSelect').val('');
                $('#stateSelect').val('');
                $('#search-input').val('');
                layui.form.render('select');
                filterProjects();
            }

            // 刷新项目数据
            window.refreshProjects = function () {
                var loading = layui.layer.load(1);

                http.get(API_CONFIG.ADMIN.PROJECTS, {
                    org_code: '',
                    design_type: API_CONFIG.DESIGNTYPE.All
                })
                    .then(function (res) {
                        layui.layer.close(loading);
                        projectTableData = res.data || [];

                        // 重新渲染整个表格
                        layui.table.render({
                            elem: '#projectTable',
                            data: projectTableData,
                            page: {
                                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'], // 完整的布局
                                prev: '上一页',
                                next: '下一页',
                                groups: 5, // 连续显示页码数
                                first: '首页',
                                last: '尾页'
                            },
                            limits: [10, 20, 50, 100],
                            limit: 10,
                            maxHeight: 'full-360',
                            cols: [[
                                { type: 'numbers', title: '序号', width: 60 },
                                { field: 'design_code', title: '设计编码', width: 150 },
                                { field: 'name', title: '项目名称', minWidth: 360 },
                                { field: 'org_name', title: '建设单位', width: 100 },
                                { field: 'designer', title: '设计人员', width: 160 },
                                {
                                    field: 'project_state',
                                    title: '状态',
                                    width: 80,
                                    align: 'center',
                                    templet: '#projectStateTpl'
                                },
                                {
                                    field: 'created_at',
                                    title: '创建时间',
                                    width: 100,
                                    templet: '#timeTpl'
                                },
                                {
                                    field: 'updated_at',
                                    title: '更新时间',
                                    width: 100,
                                    templet: function (d) {
                                        return d.updated_at ? layui.util.toDateString(d.updated_at) : '-';
                                    }
                                },
                                { fixed: 'right', title: '操作', toolbar: '#projectToolbar', width: 80, align: 'center' }
                            ]]
                        });

                        updateProjectStats(projectTableData);
                        layui.layer.msg('数据刷新完成', { icon: 1 });
                    })
                    .catch(function (err) {
                        layui.layer.close(loading);
                        layui.layer.msg('刷新失败');
                    });
            }

            // 加载项目统计
            function loadProjectStats() {
                if (projectTableData.length > 0) {
                    updateProjectStats(projectTableData);
                }
            }

            // 更新项目统计
            function updateProjectStats(data) {
                var total = data.length;
                var designCount = data.filter(item => item.project_state === 1).length;
                var acceptCount = data.filter(item => item.project_state === 2).length;
                var auditCount = data.filter(item => item.project_state === 3).length;

                document.getElementById('totalProjectCount').textContent = total;
                document.getElementById('designCount').textContent = designCount;
                document.getElementById('acceptCount').textContent = acceptCount;
                document.getElementById('auditCount').textContent = auditCount;
            }

            // 删除项目
            function deleteProject(projectData) {
                layui.layer.confirm('确定删除项目？<br>项目编码: ' + projectData.design_code + '<br>项目名称: ' + projectData.name,
                    { icon: 3, title: '删除项目确认' }, function (index) {
                        var loading = layui.layer.load(1);

                        http.delete(API_CONFIG.ADMIN.PROJECTS + '/' + projectData.design_code, {
                            params: {
                                design_type: projectData.project_state
                            }
                        })
                            .then(function (res) {
                                layui.layer.close(loading);
                                layui.layer.msg('项目删除成功');

                                // 重新加载数据
                                refreshProjects();
                            })
                            .catch(function (err) {
                                layui.layer.close(loading);
                                if (err.code === 404) {
                                    layui.layer.msg('项目不存在或已被删除');
                                } else if (err.code === 403) {
                                    layui.layer.msg('权限不足，无法删除该项目');
                                } else {
                                    layui.layer.msg('删除项目失败: ' + (err.msg || '未知错误'));
                                }
                            })
                            .finally(function () {
                                layui.layer.close(index);
                            });
                    });
            }
        });

    </script>
</body>

</html>